﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace QuanLyBepAnTuThien
{
    public partial class frmChiTietChiTieu : Form
    {
        public frmChiTietChiTieu()
        {
            InitializeComponent();
        }
        connect cn = new connect();
        private void Loaddata()
        {
            cobNguoiChi.DataSource = cn.getDataTable("tblNhanVien_DS");
            cobNguoiChi.DisplayMember = "HoTen";
            cobNguoiChi.ValueMember = "MaNV";

            cobTenChi.DataSource = cn.getDataTable("tblDungCu_NguyenLieu_DS");
            cobTenChi.DisplayMember = "TenDungCu";
            cobTenChi.ValueMember = "MaDungCu";

        }
        private void frmChiTietChiTieu_Load(object sender, EventArgs e)
        {
            Loaddata();
            dtNgayChi.Focus();
            txtDonGia.Text = "0";
            txtSoLuong.Text = "0";
            
        }

        private void btnThem_Click(object sender, EventArgs e)
        {
            gridChiTiet.AllowUserToAddRows = false;
            gridChiTiet.Rows.Add(1);
            int indexRow = gridChiTiet.Rows.Count-1;
            gridChiTiet["TenDungCu", indexRow].Value = cobTenChi.Text;
            gridChiTiet["SoLuong", indexRow].Value = txtSoLuong.Text;
            gridChiTiet["DonGia", indexRow].Value = txtDonGia.Text;
            gridChiTiet["MaDungCu", indexRow].Value = cobTenChi.SelectedValue;
            double thanhtien = double.Parse(txtSoLuong.Text) * double.Parse(txtDonGia.Text);
            gridChiTiet["ThanhTien", indexRow].Value = String.Format("{0:N0}",thanhtien);

            txtDonGia.Text = "0";
            txtSoLuong.Text = "0";
            cobTenChi.Focus();
            int i;
            double tong = 0;
            for (i = 0; i < gridChiTiet.Rows.Count; i++)
            {
                tong = tong + double.Parse(gridChiTiet.Rows[i].Cells["ThanhTien"].Value.ToString());
            }
            lbtongtien.Text = String.Format("{0:N0}",tong);
        }

        private void txtSoLuong_Leave(object sender, EventArgs e)
        {
            try
            {
                double soluong = double.Parse(txtSoLuong.Text);
            }
            catch
            {
                MessageBox.Show("Số lượng phải là số","Thông Báo",MessageBoxButtons.OK,MessageBoxIcon.Error);
                txtSoLuong.Text="";
                txtSoLuong.Focus();
            }
        }

        private void txtDonGia_Leave(object sender, EventArgs e)
        {
            try
            {
                double dongia = double.Parse(txtDonGia.Text);
            }
            catch
            {
                MessageBox.Show("Đơn giá phải là số","Thông Báo",MessageBoxButtons.OK,MessageBoxIcon.Error);
                txtDonGia.Text = "0";
                //txtDonGia.Focus();
            }
        }

        private void txtSoLuong_TextChanged(object sender, EventArgs e)
        {
            if (txtSoLuong.Text != "")
            {
                txtSoLuong.Text = String.Format("{0:N0}", double.Parse(txtSoLuong.Text));
                txtSoLuong.SelectionStart = txtSoLuong.Text.Length;
                thanhtien(txtDonGia.Text, txtSoLuong.Text);
            }
        }

        private void txtDonGia_TextChanged(object sender, EventArgs e)
        {
            if (txtDonGia.Text != "")
            {
                txtDonGia.Text = String.Format("{0:N0}", double.Parse(txtDonGia.Text));
                txtDonGia.SelectionStart = txtDonGia.Text.Length;
                thanhtien(txtDonGia.Text, txtSoLuong.Text);
            }
        }

        private void txtSoLuong_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void txtDonGia_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void btnLuuChi_Click(object sender, EventArgs e)
        {
            if (kiemtrahoten() == false)
            {
                MessageBox.Show("Nhân viên "+cobNguoiChi.Text+" chưa có trong danh sách nhân viên","Thông Báo",MessageBoxButtons.OK,MessageBoxIcon.Error);
                cobNguoiChi.Focus();
            }            
            else if(kiemtradungcu()==false)            
            {
                MessageBox.Show("Dụng cụ không có trong hệ thống!","Thông Báo",MessageBoxButtons.OK,MessageBoxIcon.Error);
                cobTenChi.Focus();
            }
            else if (gridChiTiet.Rows.Count <= 0)
            {
                MessageBox.Show("Không thể lưu phiếu chi\nBạn phải có ít nhất một mặt hàng trong phiếu", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                cobTenChi.Focus();
            }
            else
            {
                SqlTransaction trans = cn.ketnoi().BeginTransaction();
                try
                {
                    SqlCommand cmd = new SqlCommand("tblChiTieu_Them", cn.ketnoi());
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add(new SqlParameter("ngaychi", SqlDbType.DateTime)).Value = dtNgayChi.Value;
                    cmd.Parameters.Add(new SqlParameter("manv", SqlDbType.NVarChar)).Value = cobNguoiChi.SelectedValue;
                    //cmd.Transaction = trans;
                    if (cmd.ExecuteNonQuery() == 1)
                    {
                        SqlCommand cmd_max = new SqlCommand("tblChiTieu_MaChiMax", cn.ketnoi());
                        cmd_max.CommandType = CommandType.StoredProcedure;
                        object max = cmd_max.ExecuteScalar();
                        //MessageBox.Show(Convert.ToInt32(max).ToString());
                        int i;
                        for (i = 0; i < gridChiTiet.Rows.Count; i++)
                        {
                            int madungcu = int.Parse(gridChiTiet.Rows[i].Cells["MaDungCu"].Value.ToString());
                            double soluong = double.Parse(gridChiTiet.Rows[i].Cells["SoLuong"].Value.ToString());
                            double dongia = double.Parse(gridChiTiet.Rows[i].Cells["DonGia"].Value.ToString());
                            SqlCommand cmd_insert = new SqlCommand("tblChiTietChiTieu_Them", cn.ketnoi());
                            cmd_insert.CommandType = CommandType.StoredProcedure;
                            cmd_insert.Parameters.Add(new SqlParameter("machi", SqlDbType.Int)).Value = Convert.ToInt32(max);
                            cmd_insert.Parameters.Add(new SqlParameter("dungcu", SqlDbType.Int)).Value = madungcu;
                            cmd_insert.Parameters.Add(new SqlParameter("soluong", SqlDbType.Int)).Value = soluong;
                            cmd_insert.Parameters.Add(new SqlParameter("dongia", SqlDbType.Int)).Value = dongia;
                            cmd_insert.ExecuteNonQuery();
                            //cmd_insert.Transaction = trans;
                        }
                        MessageBox.Show("Lưu hóa đơn thành công!", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        this.Close();
                    }
                    trans.Commit();
                }
                catch (Exception)
                {
                    trans.Rollback();
                }
            }
        }
        private void thanhtien(string dongia, string soluong)
        {            
            if (txtDonGia.Text == "" || txtSoLuong.Text == "")
            {
                txtThanhTien.Text = "0";
            }
            else
            {
                txtThanhTien.Text=String.Format("{0:N0}",(double.Parse(dongia) * double.Parse(soluong)));
            }            

        }

        private void dtNgayChi_ValueChanged(object sender, EventArgs e)
        {
            int ngay, thang, nam;
            int n_ngay, n_thang, n_nam;
            ngay = dtNgayChi.Value.Day;
            thang = dtNgayChi.Value.Month;
            nam = dtNgayChi.Value.Year;

            n_ngay = DateTime.Now.Day;
            n_thang = DateTime.Now.Month;
            n_nam = DateTime.Now.Year;
            if (ngay > n_ngay || thang > n_thang || nam > n_nam)
            {
                MessageBox.Show("Bạn chọn ngày lập phiếu chi sai!","Thông Báo",MessageBoxButtons.OK,MessageBoxIcon.Error);
                dtNgayChi.Focus();
                dtNgayChi.Value = new DateTime(n_nam, n_thang, n_ngay);
            }

        }
        private bool kiemtrahoten()
        {
            SqlCommand cmd = new SqlCommand("tblNhanVien_KiemTraTenNV", cn.ketnoi());
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add(new SqlParameter("tennv", SqlDbType.NVarChar)).Value = cobNguoiChi.Text;
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            if (dt.Rows.Count <= 0)
            {
                return false;
            }
            return true;
        }
        private bool kiemtradungcu()
        {
            SqlCommand cmd = new SqlCommand("tblDungCuNguyenLieu_KiemTraTen",cn.ketnoi());
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add(new SqlParameter("ten",SqlDbType.NVarChar)).Value = cobTenChi.Text;
            object ob =cmd.ExecuteScalar();
            if (Convert.ToInt32(ob) <= 0)
            {
                return false;
            }
            return true;
        }
        private void cobNguoiChi_SelectedIndexChanged(object sender, EventArgs e)
        {                        
        }

        private void frmChiTietChiTieu_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnThem_Click(sender, e);
            }
            if (e.Control && e.KeyCode == Keys.S)
            {
                btnLuuChi_Click(sender, e);
            }
        }

        private void btnInPhieu_Click(object sender, EventArgs e)
        {

        }
    }
}
